﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Hotnet.Web.Utility
{
	public class ConvertEnumToSelectList
	{
		/// <summary>
		/// 通过一个枚举类型组装成 SelectList
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		public static SelectList ComposeSelectListFromEnum<T>()
		{
			return ComposeSelectListFromEnum<T>(null);
		}

		/// <summary>
		/// 通过一个枚举类型组装成 SelectList
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="defaultFirstOptionText">第一个默认选择的Text</param>
		/// <param name="defaultFirstOptionValue">第一个默认选项的Value</param>
		/// <returns></returns>
		public static SelectList ComposeSelectListFromEnum<T>(string defaultFirstOptionText, string defaultFirstOptionValue)
		{
			List<SelectListItem> list = new List<SelectListItem>();
			SelectListItem first = new SelectListItem();
			first.Text = defaultFirstOptionText;
			first.Value = defaultFirstOptionValue;
			list.Add(first);
			return ComposeSelectListFromEnum<T>(list);

		}

		private static SelectList ComposeSelectListFromEnum<T>(List<SelectListItem> list)
		{
			T[] values = (T[])Enum.GetValues(typeof(T));
			if (list == null)
				list = new List<SelectListItem>();
			for (int i = 0; i < values.Length; i++)
			{
				SelectListItem item = new SelectListItem();
				item.Text = values[i].ToString();
				item.Value = Convert.ToString((int)(Object)values[i]);
				list.Add(item);
			}
			return new SelectList(list, "Value", "Text");
		}

		/// <summary>
		/// 在SelectList 插入第一项
		/// </summary>
		/// <param name="selectList"></param>
		/// <param name="firstOptionName"></param>
		/// <param name="firstOptionValue"></param>
		/// <returns></returns>
		public static SelectList InsertFirstOption(SelectList selectList, string firstOptionName, string firstOptionValue)
		{
			SelectListItem item = new SelectListItem();
			item.Text = firstOptionName;
			item.Value = firstOptionValue;
			if (selectList == null)
			{
				List<SelectListItem> list = new List<SelectListItem>();
				list.Add(item);
				return new SelectList(list, "Value", "Text");
			}
			List<SelectListItem> items = selectList.ToList();
			items.Insert(0, item);
			return new SelectList(items, "Value", "Text");
		}
	}
}
